package com.ee.pet.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ee.pet.common.R;
import com.ee.pet.component.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {
    @PostMapping("blog")
    public R<String> uploadImage(@RequestParam("file") List<MultipartFile> image) {
        try {
            List<String> Url = new ArrayList<>();
            for (MultipartFile file : image) {
                String originalFilename = file.getOriginalFilename();
                String fileName = createNewFileName(originalFilename);
                file.transferTo(new File("/home/pet_img", fileName));
                Url.add(fileName);
             log.debug("文件上传成功，{}", fileName);
            }
//            // 获取原始文件名称
//            String originalFilename = image.getOriginalFilename();
//            // 生成新文件名
//            String fileName = createNewFileName(originalFilename);
//            // 保存文件
//            image.transferTo(new File("/home/pet_img", fileName));
            // 返回结果
            return R.success(Url.toString());
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
    @GetMapping("/blog/delete")
    public R deleteBlogImg(@RequestParam("name") String filename) {
        File file = new File("/home/pet_img", filename);
        if (file.isDirectory()) {
            return R.error("文件不存在");
        }
        FileUtil.del(file);
        return R.success("删除成功");
    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File("/home/pet_img", StrUtil.format("/blogs"));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/blogs/{}.{}", name, suffix);
    }
}
